<?php

namespace app\modules\adminuser\controllers;

use Yii;
use common\models\User;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use common\models\Tools;


/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends \app\components\AdminController
{
    public $enableCsrfValidation=false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $page_no = Tools::GetSafeParam('page_no', 1, 0);
        $condition = [];
        $condition['username'] = Tools::GetSafeParam('username', '', 1);
        $condition['mobile'] = Tools::GetSafeParam('mobile', '', 1);
        
        $data = User::getUserList($condition,$page_no);
        
        $page = Tools::showCmPager($page_no, $data['perpage'], $data['total'],$condition);
        
        $identity_auth_arr = [0=>'未认证',1=>'待审核',2=>'已认证',3=>'未通过'];
        return $this->render('index',[
            'data' => $data,
            'page' => $page,
            'condition' => $condition,
            'identity_auth_arr'=>$identity_auth_arr
        ]);
        
//        $searchModel = new UserSearch();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//
//        return $this->render('index', [
//            'searchModel' => $searchModel,
//            'dataProvider' => $dataProvider,
//        ]);
    }
    
    /***
     * 编辑用户角色
     * adminuser/user/edit-user-role
     */
    public function actionEditUserRole(){
        $post = Yii::$app->request->post();
        if(!empty($post)){
            //删除原先的角色数据
            \common\models\SysUser2role::deleteAll(['userid'=>$post['userid']]);
            $model = new \common\models\SysUser2role();
            $model->userid = $post['userid'];
            $model->roleid = $post['roleid'];
            $model->addtime = time();
            if($model->save()){
                $user = \common\models\User::findOne($post['userid']);
                $user->role_id = $post['roleid'];
                $user->save();
                return $this->redirect('/adminuser/user/index');
            }
            
        }
        
        $userid = \common\models\Tools::GetSafeParam('userid', 0, 0);
        $username = \common\models\Tools::GetSafeParam('username', '', 1);
        //列出系统所有角色
        $roles = \common\models\SysRole::find()->asArray()->all();
        
        //检测当前用户的权限
        $user_role = \common\models\SysUser2role::findOne(['userid'=>$userid]);
        $roleid = !empty($user_role) ? $user_role->roleid : 0;
        
        return $this->render('edit-user-role',['roles'=>$roles,'userid'=>$userid,'username'=>$username,'roleid'=>$roleid]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $username = Tools::GetSafeParam('username', '', 1);
        $mobile = Tools::GetSafeParam('mobile', '', 1);
        $passwd = Tools::GetSafeParam('passwd', '', 1);
        
        if($username != "" && $passwd != ""){
            $user = new User();
            $user->username = $username;
            $user->mobile = $mobile;
            $user->setPassword($passwd);
            $user->generateAuthKey();
            if($user->save()){
                \common\models\WebsocketSever::distributeServer($user->id);
                return $this->redirect(['index']);
            }
        }
        return $this->render('create');
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate()
    {
        $id = Tools::GetSafeParam('id', 0, 0);
        $username = Tools::GetSafeParam('username', '', 1);
        $mobile = Tools::GetSafeParam('mobile', '', 1);
        
        $model = $this->findModel($id);
        if ($username != "") {
            $model->username = $username;
            $model->mobile = $mobile;
            
            if($model->save()){
                return $this->redirect(['index']);
            }
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }
    
    public function actionCheckExist(){
        $userid = Tools::GetSafeParam('userid', 0, 0);
        $username = Tools::GetSafeParam('username', '', 1);
        $exist = User::checkExist($userid,$username);
        
        $output['success'] = 1;
        $output['exist'] = $exist ? 1 : 0;
        Tools::outputjson($output);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        if($this->findModel($id)->delete()){
            $output['success'] = 1;
            $output['msg'] = "删除成功！";
            Tools::outputjson($output);
        }
        else{
            $output['success'] = 0;
            $output['msg'] = "删除失败！";
            Tools::outputjson($output);
        }
//        $this->findModel($id)->delete();
//
//        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    
    /***
     * 实名认证审核列表
     */
    public function actionAuthlist(){
        $data = \common\models\User::find()->where(['identity_auth'=>1]);  //Field为model层,在控制器刚开始use了field这个model,这儿可以直接写Field,开头大小写都可以,为了规范,我写的是大写
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '2']);    //实例化分页类,带上参数(总条数,每页显示条数)
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        return $this->render('authlist',[
            'model' => $model,
            'pages' => $pages,
        ]);
    }
    
    public function actionAuth(){
        $userid = \common\models\Tools::GetSafeParam('userid', 0, 0);
        
        $model = \common\models\User::findOne(['id'=>$userid]);
        
        $identity_auth = \common\models\Tools::GetSafeParam('identity_auth', 0, 0);
        $operate_info = \common\models\Tools::GetSafeParam('operate_info', '', 1);
        
        if($identity_auth>1){
            $model->identity_auth = $identity_auth;
            $model->operate_info = $operate_info;
            $model->save();
            return $this->redirect('/adminuser/user/authlist');
        }
        
        $font_server = Yii::$app->params['server'];
        
        return $this->render('auth',['model'=>$model,'font_server'=>$font_server]);
    }
}
